{% extends "layout.html" %}

{% block extra_css %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/admin_messages.css') }}">
{% endblock %}

{% block content %}
<div class="admin-messages-container">
    <h2>留言审核管理</h2>

    <div class="tabs">
        <button class="tab-btn active" data-tab="messages">待审留言 ({{ messages|length }})</button>
        <button class="tab-btn" data-tab="replies">待审回复 ({{ replies|length }})</button>
    </div>

    <div class="tab-content active" id="messages-tab">
        {% if messages %}
            {% for message in messages %}
            <div class="message-card" data-id="{{ message.id }}">
                <div class="message-header">
                    <span class="username">{{ message.username }}</span>
                    <span class="date">{{ message.created_at }}</span>
                </div>
                <div class="message-content">
                    {{ message.content | safe }}
                </div>
                <div class="message-actions">
                    <button class="btn-approve" data-id="{{ message.id }}">批准</button>
                    <button class="btn-reject" data-id="{{ message.id }}">拒绝</button>
                    <a href="{{ url_for('messages.message_board') }}#message-{{ message.id }}" class="btn-view" target="_blank">查看原文</a>
                </div>
            </div>
            {% endfor %}
        {% else %}
            <div class="no-items">暂无待审留言</div>
        {% endif %}
    </div>

    <div class="tab-content" id="replies-tab">
        {% if replies %}
            {% for reply in replies %}
            <div class="reply-card" data-id="{{ reply.id }}">
                <div class="reply-header">
                    <span class="username">{{ reply.username }}</span>
                    <span class="date">{{ reply.created_at }}</span>
                    <span class="reply-to">回复: {{ reply.parent_username }}</span>
                </div>
                <div class="reply-content">
                    {{ reply.content | safe }}
                </div>
                <div class="reply-actions">
                    <button class="btn-approve" data-id="{{ reply.id }}">批准</button>
                    <button class="btn-reject" data-id="{{ reply.id }}">拒绝</button>
                    <a href="{{ url_for('messages.message_board') }}#message-{{ reply.parent_id }}" class="btn-view" target="_blank">查看原文</a>
                </div>
            </div>
            {% endfor %}
        {% else %}
            <div class="no-items">暂无待审回复</div>
        {% endif %}
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 标签切换
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const tabId = this.dataset.tab;

            // 更新按钮状态
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            // 更新内容显示
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.getElementById(`${tabId}-tab`).classList.add('active');
        });
    });

    // 审核操作
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('btn-approve') ||
            e.target.classList.contains('btn-reject')) {

            const btn = e.target;
            const messageId = btn.dataset.id;
            const action = btn.classList.contains('btn-approve') ? 'approve' : 'reject';
            const isReply = btn.closest('.reply-card');

            btn.disabled = true;
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';

            fetch(`/admin/${isReply ? 'reply' : 'message'}/${messageId}/${action}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 显示成功消息
                    showFlashMessage(data.message || '操作成功', 'success');

                    // 移除已处理的卡片
                    btn.closest(isReply ? '.reply-card' : '.message-card').remove();

                    // 更新计数
                    const tab = isReply ? 'replies' : 'messages';
                    const countElement = document.querySelector(`.tab-btn[data-tab="${tab}"]`);
                    const currentCount = parseInt(countElement.textContent.match(/\((\d+)\)/)[1]);
                    countElement.textContent = countElement.textContent.replace(/\(\d+\)/, `(${currentCount - 1})`);

                    // 如果没有内容了，显示提示
                    if (currentCount - 1 === 0) {
                        const tabContent = document.getElementById(`${tab}-tab`);
                        tabContent.innerHTML = '<div class="no-items">暂无待审' + (isReply ? '回复' : '留言') + '</div>';
                    }
                } else {
                    showFlashMessage(data.message || '操作失败', 'error');
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showFlashMessage('网络错误，请稍后再试', 'error');
                btn.disabled = false;
                btn.innerHTML = originalText;
            });
        }
    });

    // 显示浮动消息
    function showFlashMessage(message, type) {
        // 移除现有的消息
        const existingFlash = document.querySelector('.flash-message');
        if (existingFlash) {
            existingFlash.remove();
        }

        const flashDiv = document.createElement('div');
        flashDiv.className = `flash-message ${type}`;
        flashDiv.innerHTML = `<span>${message}</span>`;
        document.body.appendChild(flashDiv);

        // 自动消失
        setTimeout(() => {
            flashDiv.classList.add('fade-out');
            setTimeout(() => flashDiv.remove(), 500);
        }, 3000);
    }
});
</script>
{% endblock %}